package com.rd.student.jike.class4.xiayinyin.week04.day25;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class TestSemaphore {

    private static Semaphore semaphore = new Semaphore(20);

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "来到停车场");
                    if (semaphore.availablePermits() == 0){
                        System.out.println("车位不足，请等待");
                    }
                    try {
                        semaphore.acquire();
                        //添加信号量
                        System.out.println(Thread.currentThread().getName() + "进入停车场");
                        Thread.sleep(new Random().nextInt(8888));
                        System.out.println(Thread.currentThread().getName() + "开出停车场");
                        semaphore.release();
                        //移除信号量
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }
}
